<template>
  <div class="details">
    <van-nav-bar
      title="商品详情"
      left-text="返回"
      left-arrow
      @click-left="back"
    />
    <div class="details-img">
      <img :src="detailsData.large_img" alt="" />
    </div>
    <div class="pro-title">
      <h2>
        {{ detailsData.name }}<span>&yen; {{ detailsData.price }}</span>
      </h2>
      <p>{{ detailsData.enname }}</p>
    </div>
    <!-- 规格选项 -->
    <div class="rules">
      <div class="rule" v-for="(item, i) in detailsData.rulesData" :key="i">
        <div class="rule-title">{{ item.title }}</div>
        <div class="rule-items">
          <div
            :class="{ current: item.currentIndex === index }"
            v-for="(v, index) in item.rule"
            :key="index"
            @click="taggleRule(item, index)"
          >
            {{ v.title }}
          </div>
        </div>
      </div>
    </div>
    <!-- 数量 -->
    <div class="pro-count">
      <div class="count-title">选择数量</div>
      <div class="count">
        <van-stepper
          v-model="count"
          theme="round"
          button-size="22"
          disable-input
        />
      </div>
    </div>
    <!-- 商品描述 -->
    <div class="pro-details">
      <div class="desc-title">商品描述</div>
      <div class="desc-text" v-for="(item, i) in detailsData.desc" :key="i">
        {{ i + 1 }}.{{ item }}
      </div>
    </div>
    <van-goods-action>
      <van-goods-action-icon
        icon="shopping-cart"
        color="#666"
        text="购物车"
        :badge="shopCarCount ? shopCarCount : ''"
        @click="goShopCar"
      />
      <van-goods-action-icon
        icon="like"
        :color="islike ? '#307dd5' : '#666'"
        :text="islike ? '已收藏' : '收藏'"
        @click="likeAndNotlike"
      />
      <van-goods-action-button
        color="#063382"
        type="warning"
        text="加入购物车"
        @click="addShopCar"
      />
      <van-goods-action-button color="#307dd5" type="danger" text="立即购买" />
    </van-goods-action>
  </div>
</template>

<script>
import "../assets/less/details.less";
import { mapState, mapMutations } from "vuex";

export default {
  name: "Details",
  data() {
    return {
      pid: "",
      detailsData: {},
      islike: false,
      // 商品数量
      count: 1,
      // shopCarCount: 0
    };
  },
  created() {
    this.pid = this.$route.params.pid;
    this.getDetailsData();
    this.getLikeProduct();
    this.getShopCarCount();
  },
  computed: {
    ...mapState(["shopCarCount"]),
  },
  methods: {
    ...mapMutations(["changeShopCarCount"]),

    getDetailsData() {
      this.axios({
        method: "GET",
        url: this.baseURL + "/productDetail",
        params: {
          appkey: this.appkey,
          pid: this.pid,
        },
      }).then((response) => {
        // console.log(response);
        if (response.data.code == 600) {
          let data = response.data.result[0];

          let rules = ["cream", "milk", "sugar", "tem"];

          data.rulesData = [];

          rules.forEach((v) => {
            if (!data[v]) {
              return;
            }

            let rulesArr = data[v].split("/");

            let currentRule = {
              title: data[v + "_desc"],
              currentIndex: 0,
              rule: [],
            };

            rulesArr.forEach((item) => {
              let o = {
                title: item,
              };
              currentRule.rule.push(o);
            });
            data.rulesData.push(currentRule);
          });
          // 处理商品描述
          data.desc = data.desc.split(/\n/);
          this.detailsData = data;
        }
      });
    },
    // 选择规则
    taggleRule(item, index) {
      item.currentIndex = index;
    },
    // 返回上一页
    back() {
      this.$router.back();
    },
    // 跳回购物车
    goShopCar() {
      this.$router.push({ name: "ShopCar" });
    },

    // 收藏
    like() {
      let tokenString = this.$cookies.get("tokenString");
      console.log(tokenString);

      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "post",
        url: this.baseURL + "/like",
        data: {
          appkey: this.appkey,
          pid: this.pid,
          tokenString,
        },
      })
        .then((response) => {
          this.$toast.clear();
          // console.log(response);

          if (response.data.code === 700) {
            this.$toast({
              message: response.data.msg,
              forbidClick: true,
              duration: 1000,
            });
            this.$router.push({ name: "Login" });
          }

          if (response.data.code === 800) {
            this.islike = true;
          } else {
            this.$toast({
              message: response.data.msg,
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.error(err);
        });
    },

    // 查询收藏商品
    getLikeProduct() {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return;
      }

      this.axios({
        method: "GET",
        url: this.baseURL + "/findlike",
        params: {
          appkey: this.appkey,
          pid: this.pid,
          tokenString,
        },
      })
        .then((response) => {
          // console.log(response);

          if (response.data.code === 700) {
            return;
          }

          if (response.data.code === 1000) {
            if (response.data.result.length > 0) {
              this.islike = true;
            } else {
              this.islike = false;
            }
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },

    // 取消收藏
    notLike() {
      let tokenString = this.$cookies.get("tokenString");
      console.log(tokenString);

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      this.axios({
        method: "post",
        url: this.baseURL + "/notlike",
        data: {
          appkey: this.appkey,
          pid: this.pid,
          tokenString,
        },
      })
        .then((response) => {
          // console.log(response);

          if (response.data.code === 700) {
            this.$toast({
              message: response.data.msg,
              forbidClick: true,
              duration: 1000,
            });
            this.$router.push({ name: "Login" });
          }

          if (response.data.code === 900) {
            if (response.data.result === 1) {
              this.islike = false;
            }
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },

    // 切换收藏状态
    likeAndNotlike() {
      if (this.islike) {
        this.notLike();
      } else {
        this.like();
      }
    },

    // 添加购物车
    addShopCar() {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      let rules = [];
      this.detailsData.rulesData.forEach((v) => {
        rules.push(v.rule[v.currentIndex].title);
      });

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "POST",
        url: this.baseURL + "/addShopcart",
        data: {
          appkey: this.appkey,
          tokenString,
          pid: this.pid,
          count: this.count,
          rule: rules.join("/"),
        },
      })
        .then((response) => {
          this.$toast.clear();
          // console.log(response);

          if (response.data.code === 700) {
            this.$toast({
              message: response.data.msg,
              forbidClick: true,
              duration: 2000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (response.data.code === 3000) {
            if (response.data.status == 1) {
              this.$toast({
                message: response.data.msg,
                duration: 2000,
              });
              this.changeShopCarCount(this.shopCarCount + 1);
            }
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.error(err);
        });
    },

    // 查询购物车条目
    getShopCarCount() {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return;
      }

      this.axios({
        method: "GET",
        url: this.baseURL + "/shopcartRows",
        params: {
          appkey: this.appkey,
          tokenString,
        },
      })
        .then((response) => {
          // console.log(response);

          if (response.data.code === 700) {
            this.$toast({
              message: response.data.msg,
              forbidClick: true,
              duration: 1000,
            });
          }

          if (response.data.code === 8000) {
            this.changeShopCarCount(response.data.result);
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },
  },
};
</script>
